package com.ibm.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.Gson;
import com.ibm.util.exception.CPSException;

public class EntryPair implements Comparable<Number>{

	double max = Double.MIN_VALUE;
	double min = Double.MAX_VALUE;
	HashMap<String, Double> map;
	String name;
	String regex;
	
	public EntryPair(String name,String jsonStr) throws CPSException {
		this.name = name;
	    regex = ("\\Q" + name + "\\E").replace("*", "\\E.*\\Q");
		JsonNode node = JSONUtility.fromString(jsonStr);
		map = new HashMap<>();
		Iterator<String> fieldNames = node.fieldNames();
		while (fieldNames.hasNext()) {
			String field = (String) fieldNames.next();
			// special field.
			// we're not gonna to match these fields.
			if (field.equals("k") || field.equals("t")) {
				continue;
			}
			if (wildCardMath(field)) {
				Double value = node.get(field).asDouble();
				map.put(field, value);
				if (value > max) {
					max = value;
				}
				if (value < min) {
					min = value;
				}
			}
		}
	}



	
	/*
	 * Noted:
	 * return 1,-1,0
	 * 1  --> all the values is greater than the value
	 * -1 --> all the values is less than the value
	 * 0 --> some of the values is greater than the value,some don't
	 */

	public int compareTo(Number o){
		Double value = o.doubleValue();
		if (min > value) {
			return 1;
		}else if (max < value) {
			return -1;
		}
		return 0;
	}
	
	
	public String debugString(){
		return new Gson().toJson(this);
	}
	
	public String toString(){
		return new Gson().toJson(this);
	}
	
	public ObjectNode overview(){
		ObjectNode node = JSONUtility.newObjectNode();
		node.put("min", min);
		node.put("max", max);
		return node;
	}
	
	public boolean wildCardMath(String fieldName){
		return fieldName.matches(regex);
	}

	public double getMax() {
		return max;
	}

	public void setMax(double max) {
		this.max = max;
	}

	public double getMin() {
		return min;
	}

	public void setMin(double min) {
		this.min = min;
	}

	public HashMap<String, Double> getMap() {
		return map;
	}

	public void setMap(HashMap<String, Double> map) {
		this.map = map;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRegex() {
		return regex;
	}

	public void setRegex(String regex) {
		this.regex = regex;
	}



}
